package net.wyy.ssoclient.interceptor;

import net.wyy.ssocore.ServletUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Enzo Cotter on 2019/11/21.
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${sso.server.validateUrl}")
    private String ssoServerUrl;
    @Value("${sso.server.login}")
    private String ssoServerLogin;

    private RestTemplate restTemplate = new RestTemplate();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ServletUtils.printJsessionId(request,true);
        String userId = (String)request.getSession().getAttribute("userId");
        String currentLocation = getLocation(request);

        if(StringUtils.isBlank(userId)){
            // 未登陆,跳转到 sso server
            response.sendRedirect(ssoServerLogin+"?serviceUrl="+currentLocation);
            return false;
        }

        return true;
    }

    private String getLocation(HttpServletRequest request) {
        return request.getScheme()+"://"+request.getHeader("host")+request.getServletPath();
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
